<?php
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
class OrderRefund extends Base {
    public  $order_status;
    public $refund_status;
    /*
     * 初始化操作
     */
    public function initialize() {
        parent::initialize();
        $this->order_status = logic('OrderLogic')->getStatus();
        $this->refund_status = logic('OrderLogic')->getRefundStatus();
        // 订单 支付 发货状态
        View::assign('order_status',$this->order_status);
    }
    public function index(){
        if(input('?param.status')){
            $status = input('status');
        }else{
            $status = input('status')?:'all';
        }
        $goods_leixing = Db::name('goods_leixing')->where('1=1')->column('name','id');
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            if(SID){
                $map['o.sid'] = SID;
            }
            if(input('user_id')){
                $map['o.user_id'] = input('user_id');
            }
            if(input('username')){
                $map['o.username'] = input('username');
            }
            if(input('order_sn')){
                $map['o.order_sn'] = input('order_sn');
            }
            if(input('?param.status') && input('status')!='all'){
                $map['r.status'] = input('status');
            }
            if(input('?param.order_status') && input('order_status')!='all'){
                $map['o.order_status'] = input('order_status');
            }

            if(input('?param.leixing_id') && input('leixing_id')!='all'){
                $map['o.leixing_id'] = input('leixing_id');
            }
            if(input('time_start') && input('time_end')){
                $time_start = strtotime(input('time_start'));
                $time_end = strtotime(input('time_end'));
                $map['r.w_time'] = ['between',[$time_start,$time_end]];
            }
            $count = Db::name('order')->alias('o')->where($map)->count();

            $orders_status = $this->order_status;
            $field = 'r.*,o.order_sn,o.order_status';
            $list = Db::name('order_refund')
                ->alias('r')
                ->join('order o','r.order_id = o.order_id','left')
                ->field($field)
                ->where($map)
                ->order('o.order_id desc ')
                ->page($page,$limit)
                ->select();
            foreach($list as $k=>$v){
                $v['w_time'] = date('Y-m-d H:i:s',$v['w_time']);
                $v['status_str'] = $orders_status[$v['order_status']];
                $refund_status = $v['status'];
                $v['refund_status_str'] = $this->refund_status[$refund_status]??'未知';
                $list[$k] = $v;
            }

            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list]);
        }
        $shipping_list = Db::name('shipping')->field('shipping_name,shipping_code')->select();
        View::assign('shipping_list',$shipping_list);
        View::assign("goods_leixing",$goods_leixing);
        View::assign('status',$status);
        View::assign('sid',SID);
        return View::fetch();
    }

    /**
     * 导出订单
     */
    public function excel()
    {
        $page = input('page');
        $limit = input('limit')?:15;
        $map = [];
        if(SID){
            $map['o.sid'] = SID;
        }
        if(input('user_id')){
            $map['o.user_id'] = input('user_id');
        }
        if(input('username')){
            $map['o.username'] = input('username');
        }
        if(input('order_sn')){
            $map['o.order_sn'] = input('order_sn');
        }
        if(input('?param.status') && input('status')!='all'){
            $map['o.order_status'] = input('status');
        }
        if(input('?param.order_status') && input('order_status')!='all'){
            $map['o.order_status'] = input('order_status');
        }
        if(input('s_username')){
            $map['s.username|s.name'] = ['like','%'.input('s_username').'%'];
        }
        $goods_leixing = Db::name('goods_leixing')->where('1=1')->column('name','id');
        $orders_status = $this->order_status;
        $field = 'o.*,s.name s_name,s.username s_username';
        $list = Db::name('order')
            ->alias('o')
            ->join('suppliers s',' o.sid = s.id','left')
            ->field($field)
            ->where($map)
            ->order('o.order_id desc ')
            ->page($page,$limit)
            ->select();
        $count = Db::name('order')
            ->alias('o')
            ->join('suppliers s',' o.sid = s.id','left')
            ->field($field)
            ->where($map)
            ->count();
        $title = ['订单ID','会员ID','会员账号','商家账号','商家名称','订单编号','订单类型','收货人','总金额','订单状态','配送方式','物流单号','下单时间','付款时间','发货时间','收货时间'];
        $data = [];
        foreach($list as $k=>$v){
            $v['leixing_name'] = $goods_leixing[$v['leixing_id']];
            $v['status_str'] = $orders_status[$v['order_status']];
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['pay_time'] = $v['pay_time']?date('Y-m-d H:i:s',$v['pay_time']):'';
            $v['confirm_time'] = $v['confirm_time']?date('Y-m-d H:i:s',$v['confirm_time']):'';
            $v['shipping_time'] = $v['shipping_time']?date('Y-m-d H:i:s',$v['shipping_time']):'';
            $list[$k] = $v;
            $arr = [
                $v['order_id'],$v['user_id'],$v['username'],$v['s_username'],$v['s_name'],$v['order_sn'],$v['leixing_name'],$v['consignee'],
                $v['total_shop_price'],$v['status_str'],$v['shipping_name'],$v['delivery_no'],$v['add_time'],
                $v['pay_time'],$v['shipping_time'],$v['confirm_time']
            ];
            $data[] = $arr;
        }
        return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data,'title'=>$title]);
        $this->export_excel($title,$data);
    }

    /**
     * 订单详情
     * @param $order_id
     * @return mixed
     */
    public function detail(){
        $order_id = input('id');
        $order = Db::name('order')->where('order_id',$order_id)->find();
        //$order =$orderObj->append(['full_address','orderGoods'])->toArray();
        $order['orderGoods'] = Db::name('order_goods')->where('order_id',$order_id)->select();
        $province =  Db::name('region')->where(['id'=>$order['province']])->value('name');
        $city = Db::name('region')->where(['id'=>$order['city']])->value('name');
        $district = Db::name('region')->where(['id'=>$order['district']])->value('name');
        $adderss = $province.'，'.$city.'，'.$district.'，'.$order['address'];
        $order['full_address'] = $adderss;
        $user = Db::name('users')->where(['user_id'=>$order['user_id']])->find();
        View::assign('order',$order);
        View::assign('user',$user);
        //钱包
        $wallet = logic('Wallet')->getName();
        $wallet['onlinepay'] = '在线支付';
        View::assign('wallet',$wallet);
        return View::fetch();
    }
    //同意退货
    public function tuihuo_agree(){
        $id = input('order_id');
        $map = ['order_id'=>$id];
        if(SID){
            $map['sid'] = SID;
        }
        $info = Db::name('Order')->where($map)->find();
        if(!$info){
            return json(['status'=>0,'msg'=>'订单状态有误！']);
        }
        $refund_info = Db::name('order_refund')->where('id',$info['refund_id'])->order('id desc')->find();
        if(!$refund_info){
            return json(['status'=>0,'msg'=>'退款数据错误！']);
        }
        Db::startTrans();
        $save = [];
        $save['status'] = 1;
        $save['u_time'] = time();
        $save['audit_remark'] = input('renark');
        //先更新状态
        $rs = Db::name('order_refund')->where(['id'=>$info['refund_id']])->update($save);
        if(!$rs){
            Db::rollback();
            return json(['status'=>0,'msg'=>'更新订单状态失败！']);
        }
        $save = [];
        $save['status'] = 1;
        $rs = Db::name('order_refund_goods')->where(['refund_id'=>$info['id']])->update($save);

        Db::name('order_refund')->where('order_id',$id)->update(['status'=>1,'u_time'=>time()]);
        //退钱
        if($refund_info['receive']==0){
            $pay = unserialize($info['payment']);
            $memo = '订单号'.$info['order_sn'];
            foreach($pay as $wk=>$money){
                if($money>=0.01){
                    $memo1 = $memo;
                    if($wk=='onlinepay') {
                        $memo1 .= '，在线支付金额';
                        $wk = 'money';
                    }
                    $rs = qianbao($info['user_id'],$money,$wk,'退货成功',$memo1);
                    if(!$rs['status']){
                        Db::rollback();
                        return json(['status'=>0,'msg'=>'返钱失败'.$rs['msg']]);
                    }
                }
            }
            //这里不先弄销量
            //库存也不增加，货还没回来
            logic('OrderLogic')->returnBonus($info);
        }

        Db::commit();
        return json(['status'=>1,'msg'=>'退货成功，钱款已退还！']);
    }

    //拒绝退货
    public function tuihuo_refuse(){
        $id = input('order_id');
        $map = ['order_id'=>$id];
        if(SID){
            $map['sid'] = SID;
        }
        $info = Db::name('Order')->where($map)->find();
        if(!$info){
            return json(['status'=>0,'msg'=>'订单状态有误']);
        }
        $refund_info = Db::name('order_refund')->where('id',$info['refund_id'])->order('id desc')->find();
        if(!$refund_info){
            return json(['status'=>0,'msg'=>'退款数据错误！']);
        }
        Db::startTrans();
        $save = [];
        $save['status'] = 2;
        $save['u_time'] = time();
        $save['audit_remark'] = input('renark');
        //先更新状态
        $rs = Db::name('order_refund')->where(['id'=>$info['refund_id']])->update($save);
        if($rs){
            $save = [];
            $save['status'] = 2;
            $rs = Db::name('order_refund_goods')->where(['rid'=>$info['refund_id']])->update($save);
            Db::commit();
            return json(['status'=>1,'msg'=>'操作成功，可通知会员收货']);
        }else{
            Db::rollback();
            return json(['status'=>0,'msg'=>'更新订单状态失败，请联系客服处理']);
        }

    }

}
